package com.xsmart.order.services.core;

import com.xsmart.common.constant.RedisKeyConstant;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.common.util.RedisUtil;
import com.xsmart.order.dao.*;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单创建
 *
 * @author guojd
 */
@Service
public class OrderCreateService {
    @Autowired
    OrderSettleService orderSettleService;
    @Autowired
    UserAddressDao userAddressDao;
    @Autowired
    PaymentDao paymentDao;
    @Autowired
    ShippingDao shippingDao;
    @Autowired
    OrderFillsDao orderFillsDao;
    @Autowired
    GoodsManageDao goodsManageDao;
    @Autowired
    CartDao cartDao;
    @Autowired
    RedisUtil redisUtil;

    private final Logger logger = LoggerFactory.getLogger(OrderCreateService.class);

    /**
     * 创建订单
     *
     * @param requestBean 请求信息
     *                    uid: 用户ID
     *                    cart_id: 购物车id，多个采用"，"分隔
     *                    type: 支付类型
     *                    aid: 地址的id
     *                    remark: 用户备注
     *                    price: 总价
     * @return 订单创建结果
     */
    @Transactional
    public ResponseBean orderCreate(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        String buyFrom = requestBean.getRequestParamString("buyFrom");
        if (buyFrom.equalsIgnoreCase("buyCart")) {
            responseBean = orderCreateByCart(requestBean);
        } else if (buyFrom.equalsIgnoreCase("buynow")) {
            responseBean = orderCreateByNow(requestBean);
        }

        return responseBean;
    }

    /**
     * 购物车结算创建订单
     *
     * @param requestBean
     * @return
     */
    private ResponseBean orderCreateByCart(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer uid = requestBean.getRequestParamInteger("uid");
        String cartId = requestBean.getRequestParamString("cart_id");
        Integer aid = requestBean.getRequestParamInteger("aid");
        Float price = requestBean.getRequestParamFloat("price");

        if (uid == null || cartId == null || cartId.length() == 0 || aid == null || price == null || price == 0) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("请求错误");
            return responseBean;
        }
        //获取商品、判断价格
        String[] cartIds = cartId.split(",");
        ResponseBean cartInfoResponseBean = orderSettleService.orderSettle(requestBean, cartIds, uid);
        //商品判断处理失败，直接返回
        if (cartInfoResponseBean.getResult() != ResultConstant.SUCCESS) {
            cartInfoResponseBean.setMessage(cartInfoResponseBean.getMessage() + ",创建订单失败！");
            return cartInfoResponseBean;
        }

        responseBean = saveOrder(requestBean, cartInfoResponseBean, price, uid, aid);

        //删除购物车数据
        for (String anCartId : cartIds) {
            cartDao.delCart(Integer.parseInt(anCartId));
        }
        return responseBean;
    }

    /**
     * 立即结算创建订单
     *
     * @param requestBean
     * @return
     */
    private ResponseBean orderCreateByNow(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer uid = requestBean.getRequestParamInteger("uid");
        Integer aid = requestBean.getRequestParamInteger("aid");
        String remark = requestBean.getRequestParamString("remark");
        Float price = requestBean.getRequestParamFloat("price");
        Integer goodsId = requestBean.getRequestParamInteger("goodsId");
        Integer buyNum = requestBean.getRequestParamInteger("buyNum");


        if (uid == null || aid == null || price == null || price == 0 || goodsId == -1 || goodsId == null) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("请求错误");
            return responseBean;
        }
        ResponseBean goodsInfoResponseBean = orderSettleService.orderSettle(requestBean, goodsId, uid, buyNum);
        //商品判断处理失败，直接返回
        if (goodsInfoResponseBean.getResult() != ResultConstant.SUCCESS) {
            goodsInfoResponseBean.setMessage(goodsInfoResponseBean.getMessage() + ",创建订单失败！");
            return goodsInfoResponseBean;
        }

        responseBean = saveOrder(requestBean, goodsInfoResponseBean, price, uid, aid);
        return responseBean;

    }

    /**
     * 保存订单信息
     *
     * @param requestBean
     * @param cartInfoResponseBean
     * @param price
     * @param uid
     * @param aid
     * @return
     */
    private ResponseBean saveOrder(RequestBean requestBean, ResponseBean cartInfoResponseBean, Float price, Integer uid, Integer aid) {
        ResponseBean responseBean = requestBean.getResponseBean();
        String type = requestBean.getRequestParamString("type");
        String remark = requestBean.getRequestParamString("remark");
        Map<String, Object> infoMap = cartInfoResponseBean.getResultData();
        Float gPrice = MapUtils.getFloat(infoMap, "price", 0f);
        if (!gPrice.equals(price)) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("数据异常，创建订单失败，请再次尝试！");
            return responseBean;
        }
        Object objPro = MapUtils.getObject(infoMap, "pro");
        List<Map<String, Object>> goodsList = null;
        if (objPro != null && objPro instanceof List<?>) {
            goodsList = (List<Map<String, Object>>) objPro;
        }
        if (goodsList == null) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("订单内商品异常，创建订单失败，请再次尝试！");
            return responseBean;
        }
        //生成订单
        String orderSn = generalOrderSn();
        Integer orderId = orderAdd(uid, type, remark, price, infoMap, orderSn);
        if (orderId == -1) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("订单异常，创建订单失败，请再次尝试！");
            return responseBean;
        }
        //用户地址
        Map<String, Object> userAddressInfo = userAddressDao.queryUserAddress(aid);

        //保存订单商品
        saveOrderGoods(goodsList, orderId);
        //保存配送地址
        userAddressInfo.put("order_id", orderId);
        orderFillsDao.addOrderShippingInfo(userAddressInfo);

        Map<String, Object> result = new HashMap<>();
        result.put("order_id", orderId);
        result.put("order_sn", orderSn);
        result.put("pay_type", type);
        responseBean.addResultItem("result", result);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }


    /**
     * 保存订单商品
     *
     * @param goodsList 订单商品
     * @param orderId   订单id
     */
    private void saveOrderGoods(List<Map<String, Object>> goodsList, Integer orderId) {
        for (Map<String, Object> proInfoMap : goodsList) {
            Integer goodsId = MapUtils.getInteger(proInfoMap, "goods_id");
            int cartNum = MapUtils.getIntValue(proInfoMap, "cart_num");
            //保存订单商品
            Map<String, Object> goodsInfoMap = new HashMap<>();
            //订单ID，自增ID
            goodsInfoMap.put("order_id", orderId);
            //商品id
            goodsInfoMap.put("goods_id", goodsId);
            //商品唯一货号
            goodsInfoMap.put("goods_sn", MapUtils.getString(proInfoMap, "goods_sn"));
            //商品名称
            goodsInfoMap.put("goods_name", MapUtils.getString(proInfoMap, "goods_name"));
            //商品的购买数量
            goodsInfoMap.put("goods_number", cartNum);
            //成本价
            goodsInfoMap.put("cost_price", MapUtils.getFloatValue(proInfoMap, "cost_price"));
            //商品市场价
            goodsInfoMap.put("market_price", MapUtils.getFloatValue(proInfoMap, "market_price"));
            //商品销售价格
            goodsInfoMap.put("goods_price", MapUtils.getFloatValue(proInfoMap, "goods_price"));
            //购买该商品时所选择的属性
            goodsInfoMap.put("goods_attr", MapUtils.getString(proInfoMap, "goods_attr", "无"));
            //商品属性ID
            goodsInfoMap.put("goods_attr_id", MapUtils.getIntValue(proInfoMap, "goods_attr_id", -1));
            //是否赠品，0否，其他为优惠活动的ID
            goodsInfoMap.put("is_gift", 0);
            //是否是实物，1是，0否
            goodsInfoMap.put("is_real", 1);
            //父商品ID，-1为无父商品ID，其他为本商品为父商品的配件
            goodsInfoMap.put("parent_goods_id", -1);
            orderFillsDao.addOrderGoods(goodsInfoMap);
            updateGoodsNumber(goodsId, cartNum);
        }
    }

    /**
     * 生成订单
     *
     * @param uid         用户id
     * @param type        支付类型
     * @param remark      留言
     * @param price       订单金额
     * @param cartInfoMap 购物车信息
     * @return 订单id，-1为失败
     */
    private Integer orderAdd(Integer uid, String type, String remark, Float price, Map<String, Object> cartInfoMap, String orderSn) {
        //支付方式
        Map<String, Object> paymentType = paymentDao.queryPaymentType(type);
        //物流处理
        Map<String, Object> shippingType = shippingDao.queryshippingType("default");

        Map<String, Object> orderInfoMap = new HashMap<>();
        //会员资料自增id
        orderInfoMap.put("user_id", uid);
        //配送方式ID，自增ID
        orderInfoMap.put("shipping_id", MapUtils.getIntValue(shippingType, "shipping_id", -1));
        //支付方式自增id
        orderInfoMap.put("pay_id", MapUtils.getIntValue(paymentType, "pay_id", -1));
        //订单号，生成规则：时间+5位自增
        orderInfoMap.put("order_sn", orderSn);
        //订单附言,由用户提交订单前填写
        orderInfoMap.put("postscript", remark);
        //订单金额
        orderInfoMap.put("goods_amount", price);
        //配送费用
        orderInfoMap.put("shipping_fee", MapUtils.getIntValue(cartInfoMap, "yun", 0));
        //应付款金额
        orderInfoMap.put("order_amount", price);
        //创建订单
        orderFillsDao.addOrder(orderInfoMap);
        return MapUtils.getInteger(orderInfoMap, "order_id", -1);
    }

    /**
     * 生成订单号
     * 订单号，生成规则：时间+5位自增
     *
     * @return 订单号
     */
    private String generalOrderSn() {
        String snInt = "0";
        if (redisUtil.exists(RedisKeyConstant.ORDER_SN_INT)) {
            snInt = redisUtil.get(RedisKeyConstant.ORDER_SN_INT);
        } else {
            redisUtil.set(RedisKeyConstant.ORDER_SN_INT, "1");
        }
        int iSnInt = Integer.parseInt(snInt);
        iSnInt++;
        if (iSnInt > 99999) {
            iSnInt = 1;
        }
        redisUtil.set(RedisKeyConstant.ORDER_SN_INT, String.valueOf(iSnInt));
        SimpleDateFormat df = new SimpleDateFormat("YYYYMMddHHmmss");
        return df.format(System.currentTimeMillis()) + String.format("%05d", iSnInt);
    }

    /**
     * 更新商品库存
     *
     * @param goodsId 商品id
     * @param cartNum 订单商品数量
     */
    private void updateGoodsNumber(Integer goodsId, int cartNum) {
        goodsManageDao.updateGoodsNumber(goodsId, cartNum);
    }

}
